package org.example.repeater.server;

import com.github.benmanes.caffeine.cache.Cache;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.example.repeater.handler.ClientHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

import static org.example.repeater.message.Constant.clientPref;

public class clientServer {
    public static void start(String address, Cache<String, Object> caffeineCache) throws InterruptedException {
        Logger log = LoggerFactory.getLogger(clientServer.class);
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup group = new NioEventLoopGroup();;
        String[] split = address.split(":");
        String ip = split[0];
        int port = Integer.parseInt(split[1]);
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                             socketChannel.pipeline().addLast(
                                     new ClientHandler( address,caffeineCache)
                             );
                        }
                    });

            // 连接到服务器
            ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
            log.info("服务启动成功,转发到：{}", address);
            // 等待连接关闭
            channelFuture.channel().closeFuture().sync();
        }finally {
            // 关闭释放资源
            group.shutdownGracefully().sync();
        }
    }

    public  static void close(String key, RedisTemplate redisTemplate,Cache<String, Object> caffeineCache) {
        List<String> range = redisTemplate.opsForList().range(key, 0, -1);
        //caffeineCache.put(dataPref+key, range);
        ChannelHandlerContext clinentCtx = (ChannelHandlerContext) caffeineCache.getIfPresent(clientPref + key);
        if (clinentCtx!=null){
            clinentCtx.close();
        }
    }


}
